/****
  课程实例管理
****/
<template>
  <div class=" inside-comment">
    <div class="top-info">
      <!-- <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="getCourseInstanceList" /> -->
      <el-button type="primary" @click="addInstance">新增期数课程</el-button>
    </div>
    <RuifoxTable
      v-loading="tableLoading"
      :table-data="courseData"
      :field-list="fieldList"
      :default-index="true"
      :default-checkbox="false"
      :lazy="true"
    >
      <!-- <template #default-checkbox="{ element }">
        <div class="table-div-check">
          <el-checkbox
            class="unmover"
            v-model="element.checked"
            @change="handleCheckTable(element.id)"
            size=""
          />
        </div>
      </template> -->
      <!-- 课程封面图 -->
      <!-- <template #coverImg="{ element }" >
        <img :src="element.coverImg" alt="" class="course-thumb">
      </template> -->
      <!-- 课程类型列 -->
      <template #type="{ element }" >
        <el-tag v-if="element.type == 'PUBLIC'" type="primary">公开</el-tag>
        <el-tag v-if="element.type == 'PRIVATE'" type="primary">私有</el-tag>
        <!-- <el-tag v-if="element.type == ORGANIZATION" type="success">组织</el-tag> -->
      </template>

      <!-- 课程状态 -->
      <template #status="{ element }" >
        <el-tag v-if="element.status == 'DRAFT'" type="primary">草稿</el-tag>
        <el-tag v-if="element.status == 'UNDER_REVIEW'" type="warning">审核中</el-tag>
        <el-tag v-if="element.status == 'PUBLISHED'" type="success">已发布</el-tag>
        <el-tag v-if="element.status == 'UNDERWAY'" type="success">进行中</el-tag>
        <el-tag v-if="element.status == 'FINISHED'" type="info">已结束</el-tag>
      </template>

      <!-- 章节解锁 -->
      <template #chapterUnlockType="{ element }" >
        <el-tag v-if="element.chapterUnlockType == 'FREELY'" type="primary">自由学习</el-tag>
        <el-tag v-if="element.chapterUnlockType == 'SEQUENCE'" type="primary">顺序解锁</el-tag>
        <el-tag v-if="element.chapterUnlockType == 'ITEM_CUSTOM'" type="primary">自定义解锁</el-tag>
      </template>

      <template #startTime="{ element }">
        <span v-if="element.startTime">{{ dayjs(element.startTime).format("YYYY-MM-DD") }}</span>
        <span v-else>-</span>
      </template>

      <template #endTime="{ element }">
        <span v-if="element.endTime">{{ dayjs(element.endTime).format("YYYY-MM-DD") }}</span>
        <span v-else>-</span>
      </template>
      <template #options="{ element }">
        <div class="table-td-option unmover">
          <el-button
            type="primary"
            link
            @click="editCourseInfo(element)"
          >
            编辑
          </el-button>
          <el-button
            type="primary"
            link
            @click="copyCourseInfo(element)"
          >
            复制
          </el-button>
          <el-button
            type="primary"
            link
            @click="removeCourse(element)"
          >
            删除
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link unmover">
              <i class="iconfont">&#xe78d;</i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="element.status != 'DRAFT'" @click="changeInstanceStatus(element,'DRAFT(draft,草稿)')">草稿</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'UNDER_REVIEW'" @click="changeInstanceStatus(element,'UNDER_REVIEW(underReview,审核中)')">审核中</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'PUBLISHED'" @click="changeInstanceStatus(element,'PUBLISHED(published,已发布)')">已发布</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'UNDERWAY'" @click="changeInstanceStatus(element,'UNDERWAY(underway,进行中)')">进行中</el-dropdown-item>
                <el-dropdown-item v-if="element.status != 'FINISHED'" @click="changeInstanceStatus(element,'FINISHED(finished,已结束)')">已结束</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
      
    </RuifoxTable>
    <!-- 分页器 -->
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :pageChoose="isPageChooseBtn"
      :checkedNum="checkedNum"
      :canChoose="false"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @invertChoose="handleInvertChoose"
      @refreshList="getCourseInstanceList"
    />
    <!-- 课程实例信息 编辑对话框 -->
    <el-dialog v-model="addInstanceVisible" :title="addInstanceFlag?'新增同期课程':'编辑课程信息'" width="500px" class="addCourse-dialog">
      <el-form :model="addInstanceForm" label-width="90px">
        <el-form-item label="本期名称" prop="name">
          <el-input placeholder="输入本期名称" v-model="addInstanceForm.name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="本期封面图" prop="coverImg">
          <div class="form-img" @click="handleUpload('thumb')">
            <div class="has-img" v-if="addInstanceForm.coverImg">
              <img :src="addInstanceForm.coverImg" alt="">
              <span @click.stop="handleRemoveImg('thumb')">
                <el-icon><Delete /></el-icon>
              </span>
            </div>
            <el-icon v-else><Plus /></el-icon>
          </div>
        </el-form-item> -->
        <el-form-item label="本期开始时间" prop="time">
          <el-date-picker
            v-model="addInstanceForm.startTime"
            type="date"
            placeholder="选择开始时间"
            :size="size"
          />
        </el-form-item>
        <el-form-item label="本期结束时间" prop="time">
          <el-date-picker
            v-model="addInstanceForm.endTime"
            type="date"
            placeholder="选择结束时间"
            :size="size"
          />
        </el-form-item>
        <!-- <el-form-item label="负责人" prop="type">
          <el-input placeholder="输入负责人" v-model="addInstanceForm.principalId"></el-input>
        </el-form-item> -->
        <el-form-item label="课程学分" prop="type">
          <el-input-number v-model="addInstanceForm.credit" :precision="1" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="章节解锁" prop="type">
          <el-select v-model="addInstanceForm.chapterUnlockType" placeholder="选择课程章节解锁类型" style="width: 240px">
            <el-option
              v-for="item in courseUnlockType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
       
        <el-form-item label="清除学习记录" prop="type">
          <el-switch v-model="addInstanceForm.clearProcessWhenTestFailed" />
          <el-popover
            placement="top-start"
            :width="220"
            trigger="hover"
            content="章节测试不同过将清除用户该章节的学习记录，需要重新学习"
          >
            <template #reference>
              <el-icon color="#ff9700" size="16px" style="margin-left: 5px;"><QuestionFilled /></el-icon>
            </template>
          </el-popover>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addInstanceVisible = false">取消</el-button>
          <el-button type="primary" @click="appendInstance">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片上传 -->
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" :modelId="1" @getFileList="insertFiles" :isToJpg="true"></FilesUpload>
  
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import { 
  selectPageInstance,
  createInstance,
  updateInstance,
  deleteInstance,
  copyInstance,
  changeStatusInstance
} from '@/api/instance'
import { tableList as mixTable } from "@ruifox-cms/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { FilesUpload } from "@ruifox-cms/components"
import { formatDate } from '@/utils/tools'

const props = defineProps({
  theCourseId: {
    type: String,
    default: ""
  },
})
const theCourseId = ref(props.theCourseId);
console.log("theCourseId.value",theCourseId.value);

const defaultCourseFormData = {
  courseId: theCourseId.value,
  // coverImg: "",
  // scheduleId: "", //排课
  // principalId: "",  //负责人
  credit: "",  //学分
  chapterUnlockType: "",  //课程章节解锁类型,可用值:FREELY(freely,自由学习),SEQUENCE(sequence,顺序解锁),ITEM_CUSTOM(item_custom,自定义解锁)
  startTime: "",
  endTime: "",
  clearProcessWhenTestFailed: false //章节测试不同过是否清除学习记录
};
const addInstanceForm =  ref({ ...defaultCourseFormData });

//表格数据
const {
  queryData,
  tableData: oriTableData,
  tableLoading,
  checkedNum,
  // isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // isAllSearch,
  // getTableData,
  //   handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  // handleAllChoose,
  handleInvertChoose,
  // handleCheckTable,
  // handleResetPagination,
} = mixTable({
  getListApi: selectPageInstance,
  // batchFuncApi: deleteByIdsCourse,
});


//分页器
const defaultQuery = reactive({
  total:10,
  currentPage: 1,
  pageSize: 10,
  courseId: [theCourseId.value],
  lecturers: "",  //讲师
  // type: "",  //课程类型,可用值:PUBLIC,PRIVATE,ORGANIZATION
  // needCheck: false,
  startTime: "",
  endTime: "",
  finish: false, //是否结束
  // clearProcessWhenTestFailed: false
});

Object.assign(queryData, defaultQuery);
const courseData = ref([]);

//修改课程状态
const changeInstanceStatus = async (row, status) => { 
  const res = await changeStatusInstance({
    id: row.id,
    status: status
  })
  if(res.code === 20000){
    ElMessage.success("修改成功");
    getCourseInstanceList()
  }
}

//章节解锁类型
const courseUnlockType = ref([
  { label: "自由学习", value: 'FREELY' },
  { label: "顺序解锁", value: 'SEQUENCE' },
  { label: "自定义解锁", value: 'ITEM_CUSTOM' },
]);

//编辑课程信息
const addInstanceFlag = ref(false)
const addInstanceVisible = ref(false)

const addInstance = () => {
  addInstanceVisible.value = true
  addInstanceFlag.value = true
}
const editCourseInfo = (row) => {
  addInstanceVisible.value = true
  addInstanceFlag.value = false
  console.log("row",row);
  let newData = {...row};
  addInstanceForm.value = newData
  // addInstanceForm.value.time= [newData.startTime,newData.endTime]
}
//提交课程
const appendInstance = async () => {
  addInstanceForm.value.courseId = theCourseId.value
  addInstanceForm.value.startTime = formatDate(addInstanceForm.value.startTime,"yyyy-MM-dd hh:mm:ss");
  addInstanceForm.value.endTime = formatDate(addInstanceForm.value.endTime,"yyyy-MM-dd hh:mm:ss");
  // addInstanceForm.value.clearProcessWhenTestFailed = false
  //判断课程状态 调用增加或者修改 课程
  if (addInstanceFlag.value) {
    const res =  await createInstance(addInstanceForm.value)
    if(res.code == 20000) {
      ElMessage.success('创建成功')
    } 
  } else {
    const res = await updateInstance(addInstanceForm.value)
    if(res.code == 20000) {
      ElMessage.success('编辑成功');
      addInstanceForm.value =  { ...defaultCourseFormData };
    } 
  }
  addInstanceVisible.value = false
  await getCourseInstanceList();
}

//获取课程实例列表数据
const getCourseInstanceList = async () => {
  queryData.courseIds = [theCourseId.value]
  console.log("queryData",queryData);
  console.log("theCourseId.value",theCourseId.value);
  
  const res = await selectPageInstance(queryData)
  if (res.code === 20000) {
    courseData.value = res.data.list
    oriTableData.value = res.data.list;
    queryData.total = res.data.total;
  }
} 

// 批量操作
// const batchOptions = ref([
//   { name: "删除", value: "delete", icon: "&#xe74b;" }
// ]);
// const handleBatchOptions = (data) => {
//   if (data === "delete") {
//     handleBatchDelete();
//   } 
// };

//复制课程实例
const copyCourseInfo = async (row) => {
  console.log(row);
  const res = await copyInstance({
    courseInstanceId: row.id
  });
  if(res.code === 20000){
    getCourseInstanceList()

  }

}

//删除课程
const removeCourse = async (row) => {
  console.log(row);
  
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选期课程？</p><span style="font-size: 14px;color: #FF5240;">删除后该期课程将消失</span></div>',
    "删除确认",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  ).then(() => {
    deleteInstance({'id': row.id}).then(() => {
      getCourseInstanceList();
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
    });
  });
 
}

//表格展示字段
const fieldList = ref([
  {
    title: "课程名称",
    name: "name",
  },
  // {
  //   title: "课程封面",
  //   name: "coverImg",
  // },
  // {
  //   title: "排课",
  //   name: "scheduleId",
  // },
  // {
  //   title: "负责人",
  //   name: "principalId",
  // },
  // {
  //   title: "学分",
  //   name: "credit",
  // },
 
  {
    title: "课程状态",
    name: "status",
  },
  {
    title: "开始时间",
    name: "startTime",
  }, 
  {
    title: "结束时间",
    name: "endTime",
  },
  {
    title: "章节解锁",
    name: "chapterUnlockType",
  },
  {
    title: "操作",
    name: "options",
    width: 180,
  },
]);

// watch(
//   () => props.courseInstanceId,
//   (newCourseId) => {
//     theCourseId.value = newCourseId;
//   },
//   { immediate: true } // 立即执行一次，确保初始值也能触发
// );
onMounted(async () => {
  console.log("theCourseId.value",theCourseId.value);
  await getCourseInstanceList()

})
</script>

<style scoped lang="scss">
.top-info{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  .right-box{
    display: flex;
    button{
      margin-left: 10px;
    }
  }
}
.course-thumb{
  max-width: 95%;
  height: auto;
}

.form-img{
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  .has-img{
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    img{
      max-width: 100%;
      max-height: 100%;
    }
    span{
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }
    &:hover{
      span{
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  } 
}


</style>
